package com.gec.zhs.aop;

import com.gec.zhs.exception.ZhsException;
import com.gec.zhs.log.ZhsLogin;
import com.gec.zhs.utils.Result;
import com.gec.zhs.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @author zhs
 * @version 1.0
 * @date 2025-08-25
 * @description
 */
@Aspect
@Component
@Slf4j
public class ZhsLoginAop {

    @Around("execution(* com.gec.zhs.controller..*.*(..))&& @annotation(com.gec.zhs.log.ZhsLogin)")
    public Object Login(ProceedingJoinPoint joinPoint) throws Throwable {
        long starTime = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        ZhsLogin zhsLogin = method.getAnnotation(ZhsLogin.class);
        if (zhsLogin != null) {
            log.info("用户登录校验开始");
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                log.info("用户登录校验失败");
                throw new ZhsException(ResultCodeEnum.USER_NOT_LOGIN);
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("用户登录校验结束,耗时{}ms", endTime - starTime);
        return joinPoint.proceed();
    }
}
